package com.csu.device.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.csu.analysis.service.MeasureService;
import com.csu.analysis.service.XiaoMiService;
import com.csu.device.dao.BehaviorDao;
import com.csu.device.dao.HardWareDao;
import com.csu.device.entity.Behavior;
import com.csu.device.entity.Device;
import com.csu.device.entity.DeviceRela;
import com.csu.device.service.HardWareService;
import com.csu.push.HttpMessagePush;
import com.csu.push.WebSocketPush;
import com.csu.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class HardWareServiceImpl implements HardWareService {

    @Autowired
    private HardWareDao hardWareDao;

    @Autowired
    private MeasureService measureService;

    @Autowired
    private BehaviorDao behaviorDao;

    @Autowired
    private XiaoMiService xiaoMiService;

    @Override
    public List<Map<String, Object>> findAll() {
        return hardWareDao.findHrd();
    }


    @Override
    public void initDeviceData(Map<String, String> map) {

        //step1 加载硬件设备数据
        List<Device> deviceList = hardWareDao.findAllDeviceToRedis(map);

        //step2 刷新硬件设备
        for (Device device : deviceList) {

            if (RedisUtil.hasKey(device.getDeviceSn())) {
                Device ds = (Device) RedisUtil.get(device.getDeviceSn());
                //保留上次设备的传输记录
                device.setJsonArray(ds.getJsonArray());
                device.setBehavior(ds.getBehavior());
                device.setJsonObject(ds.getJsonObject());
            }
            RedisUtil.del(device.getDeviceSn());
            RedisUtil.set(device.getDeviceSn(), device);


        }

    }

    /**
     * 一键报警异常
     *
     * @param jsonParam
     */
    private void oneKey(JSONObject jsonParam) {
        String deviceSn = jsonParam.getString("deviceSn");
        Device device = (Device) RedisUtil.get(deviceSn);
        if (null == device) {
            return;
        }
        if (device.getOneKey() == 0) {

            this.callPolice(3, "一键报警呼救", device, 5);
        }
        return;
    }


    @Override
    public void deviceProsson(JSONObject jsonParam) throws Exception {
        String deviceType = jsonParam.getString("deviceType");//设备类型
        String deviceSn = jsonParam.getString("deviceSn");//设备编号
        String remark = jsonParam.getString("Remark");
        String gatewayId = jsonParam.getString("gatewayId");//网关
        if ("XiaoMi".equals(deviceType)) {//环境检测设备

            //是否是一键呼救
            this.oneKey(jsonParam);

            xiaoMiService.todoDeviceByXiaoMi(jsonParam, deviceSn);
            return;
        }
        if ("RFID_Tag".equals(deviceType)) {//刷卡需要查询网关动作
            this.rfId(deviceSn, gatewayId);
        }
        if ("Thermometer".equals(deviceType)) {//耳温枪
            measureService.thermometer(jsonParam.getString("deviceData"), deviceSn, remark);
        }
        if ("Oximeter".equals(deviceType)) {//血氧
            measureService.oximeter(jsonParam.getString("deviceData"), deviceSn, remark);
        }
        if ("Sphygmomanometer".equals(deviceType)) {//血压
            measureService.sphygmomanometer(jsonParam.getString("deviceData"), deviceSn, remark);
        }
        if ("Glucometer".equals(deviceType)) {//血血糖
            measureService.glucometer(jsonParam.getString("deviceData"), deviceSn, remark);
        }


    }

    @Override
    public List<Map<String, Object>> findAllHardware() {
        return hardWareDao.findAllHardware();
    }

    @Override
    public Behavior getDevRelaToDo(List<DeviceRela> deviceRelas, String deviceSn) {
        Device device = (Device) RedisUtil.get(deviceSn);
        Behavior behaviorDO = new Behavior();
        for (DeviceRela deviceRela : deviceRelas) {
            if (0 == deviceRela.getBindingType()) {
                behaviorDO.setGatewayId(deviceRela.getDeviceBindingId());
            }
            if (1 == deviceRela.getBindingType()) {
                behaviorDO.setFamilyUserId(deviceRela.getDeviceBindingId());
                behaviorDO.setFamilyUserName(deviceRela.getName());
            }
            if (2 == deviceRela.getBindingType()) {
                behaviorDO.setFamilyId(deviceRela.getDeviceBindingId());
                behaviorDO.setFamilyName(deviceRela.getName());
            }
            if (3 == deviceRela.getBindingType()) {
                behaviorDO.setSceneId(deviceRela.getDeviceBindingId());
                behaviorDO.setSceneName(deviceRela.getName());
            }
        }
        behaviorDO.setSite(device.getSite());
        behaviorDO.setStieLeft(device.getStieLeft());
        behaviorDO.setDeviceName(device.getDeviceName());

        behaviorDO.setEquipmentId(deviceSn);
        return behaviorDO;
    }

    @Override
    public void callPolice(Integer level, String remark, Device device, Integer behaviorType) {
        Behavior behavior = this.getDevRelaToDo(device.getDeviceRelas(), device.getDeviceSn());
        behavior.setLevel(level);
        behavior.setAnomalies(1);//报警设置为1
        behavior.setStartTime(new Date());
        behavior.setRemark(remark);
        behavior.setBehaviorType(behaviorType);
        behaviorDao.addBehavior(behavior);

        //页面推送
        WebSocketPush.errorPush(behavior);

        //app推送给护工 todo
        try{
            HttpMessagePush.getHgId(behavior.getFamilyUserId(),behavior.getRemark());
        }catch (Exception e){

        }

    }


    @Override
    public List<Map<String, String>> gpsHis(Map<String, Object> map) {
        List<Map<String,String>> list= hardWareDao.getUserGps(map);
        if(list.isEmpty() || list.size()>1)return null;
        map.put("device_sn",list.get(0).get("device_sn"));
        map.put("userName",list.get(0).get("name"));
        return hardWareDao.gpsHis(map);
    }

    @Override
    public List<Map<String, Object>> bedmatHis(Map<String, Object> map) {
        List<Map<String,String>> list= hardWareDao.getUserBedmat(map);
        if(list.isEmpty() || list.size()>1)return null;
        map.put("device_sn",list.get(0).get("device_sn"));
        map.put("userName",list.get(0).get("name"));
        return hardWareDao.bedmatHis(map);
    }

    /**
     * ifid 刷卡推送
     *
     * @param deviceSn
     * @param gatewayId
     */
    private void rfId(String deviceSn, String gatewayId) {
        Device user = (Device) RedisUtil.get(deviceSn);

        if (null == user) {//找不到就开卡
            WebSocketPush.ifidPush(deviceSn, "RFID");
            return;
        }

        Device gateway = null;
        if(null!=gatewayId && !"".equals(gatewayId)){
            if(null!=RedisUtil.get(gatewayId)){
                gateway=(Device) RedisUtil.get(gatewayId);
            }


        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceSn", deviceSn);
        //获取绑定的老人信息
        for (DeviceRela rela : user.getDeviceRelas()) {
            if (rela.getBindingType() == 1) {
                jsonObject.put("userId", rela.getDeviceBindingId());
                jsonObject.put("userName", rela.getName());
            }
        }
        jsonObject.put("gatewayId", gatewayId);


        if(null!=gateway && null!=gateway.getDeviceRelas()){
            //获取绑定的网关功能
            for (DeviceRela rela : gateway.getDeviceRelas()) {
                if (null != rela.getBindingType() && rela.getBindingType() == 0) {
                    jsonObject.put("gatewayType", rela.getDeviceBindingId());
                    jsonObject.put("gatewayName", rela.getName());
                }
            }
        }

        try {
            //推送数据
            HttpMessagePush.ifidPush(jsonObject);

            WebSocketPush.ifidPush2(gatewayId,jsonObject);
        } catch (Exception e) {

        }
    }

    private String getUserIdByIfid(String remark) {
        String userId = "";
        Device user = (Device) RedisUtil.get(remark);

        if (null == user) {
            return null;
        }

        //获取绑定的老人信息
        for (DeviceRela rela : user.getDeviceRelas()) {
            if (rela.getBindingType() == 1) {
                userId = rela.getDeviceBindingId();
            }
        }
        return userId;
    }

    /**
     * 保存行为信息
     *
     * @param level
     * @param jsonObject
     * @param deviceSn
     */
    public void addBehavior(Integer behaviorType, Integer level, JSONObject jsonObject, String deviceSn) {
        Device device = (Device) RedisUtil.get(deviceSn);
        Behavior behavior = this.getDevRelaToDo(device.getDeviceRelas(), deviceSn);
        if (behavior.getFamilyUserId() == null) {
            behavior.setFamilyUserId(jsonObject.getString("userId"));
        }
        behavior.setLevel(level);
        behavior.setAnomalies(jsonObject.getInteger("anomalies"));
        behavior.setDataValue(jsonObject.toJSONString());
        behavior.setStartTime(new Date());
        behavior.setBehaviorType(behaviorType);
        behaviorDao.addBehavior(behavior);
    }
}
